package cn.maihe.elg.operation.supports.electronicseal.kt.cloudsign.service;

import cn.maihe.elg.operation.model.dto.InnerBaseResp;
import cn.maihe.elg.operation.model.enums.AttachmentFileType;
import cn.maihe.elg.operation.model.enums.ContractStatus;
import cn.maihe.elg.operation.model.enums.ContractType;
import cn.maihe.elg.operation.repository.entity.*;
import cn.maihe.elg.operation.service.business.BidCustomerService;
import cn.maihe.elg.operation.service.business.KtCustomerService;
import cn.maihe.elg.operation.service.order.AcceptOrderContractService;
import cn.maihe.elg.operation.service.order.GuaranteeAttachmentInfoService;
import cn.maihe.elg.operation.service.system.OrganizationService;
import cn.maihe.elg.operation.supports.electronicseal.kt.KtConfig;
import cn.maihe.elg.operation.supports.electronicseal.kt.cloudsign.BaseKtCloudSignService;
import cn.maihe.elg.operation.supports.electronicseal.kt.cloudsign.dto.ContractGetUrlRespDTO;
import cn.maihe.elg.operation.supports.electronicseal.kt.cloudsign.dto.ContractPushReqDTO;
import cn.maihe.elg.operation.supports.electronicseal.kt.cloudsign.dto.ContractPushRespDTO;
import cn.maihe.elg.operation.supports.electronicseal.kt.cloudsign.enums.CloudSignInterfaceEnum;
import cn.maihe.elg.operation.supports.system.ElgResourceService;
import cn.maihe.elg.operation.utils.IdGenerate;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.Instant;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @Description
 * @Author WJH
 * @Date 2022/09/07
 */
@Service
@Slf4j
public class ContractUploadService extends BaseKtCloudSignService<Map, Map> {
    @Resource
    private GuaranteeAttachmentInfoService guaranteeAttachmentInfoService;
    @Resource
    private BidCustomerService bidCustomerService;
    @Resource
    private ContractPushService contractPushService;
    @Resource
    private ContractGetUrlService contractGetUrlService;
    @Resource
    private ElgResourceService elgResourceService;
    @Resource
    private AcceptOrderContractService acceptOrderContractService;
    @Resource
    private KtCustomerService ktCustomerService;
    @Resource
    private OrganizationService organizationService;
    @Resource
    private PdfAutoStampService pdfAutoStampService;

    public static final String applyFileName = "申请书";
    public static final String protocolFileName = "协议书";

    public ContractUploadService(KtConfig ktConfig) {
        super(ktConfig);
    }

    @Override
    protected CloudSignInterfaceEnum serviceName() {
        return CloudSignInterfaceEnum.contractUpload;
    }

    @Override
    public InnerBaseResp<?> doRequest(String traceId, Map reqDTO) {
        return super.doRequest(traceId, reqDTO);
    }

    @Transactional(rollbackFor = Exception.class)
    public String contractUpload(AcceptOrderInfoDO curDO) {
        String traceId = curDO.getAcceptOrderNo();
        String acceptOrderNo = curDO.getAcceptOrderNo();
        Long bidCustomerId = curDO.getBidCustomerId();
        Long orgId = curDO.getOrgId();

        Map<String, String> fileNameAndPathMap = Maps.newHashMap();
        String applyFileKey = "applyFile";
        String protocolFileKey = "protocolFile";
        fileNameAndPathMap.put(applyFileKey, guaranteeAttachmentInfoService.getGuaAttPath(acceptOrderNo, AttachmentFileType.TYPE_12).normalize().toString());
        fileNameAndPathMap.put(protocolFileKey, guaranteeAttachmentInfoService.getGuaAttPath(acceptOrderNo, AttachmentFileType.TYPE_13).normalize().toString());
        //1.上传签署文件
        InnerBaseResp<?> innerBaseResp = this.doRequest(traceId, fileNameAndPathMap);
        Map respDTO = this.parseInnerBaseResp(innerBaseResp);
        String applyFileId = (String) respDTO.get(applyFileKey);
        String protocolFileId = (String) respDTO.get(protocolFileKey);

        BidCustomerDO bidCustomer = bidCustomerService.selectById(bidCustomerId);
        KtCustomerDO bidKtCustomerDO = ktCustomerService.selectByBidderId(bidCustomerId,"1");
        OrganizationDO organizationDO = organizationService.getOrganization(orgId);
        KtCustomerDO orgKtCustomerDO = ktCustomerService.selectByOrgId(orgId,"1");

        String bidderName = bidCustomer.getBidderName();
        String bidderCreditCode = bidCustomer.getBidderCreditCode();
        String bidAuthMobile = bidKtCustomerDO.getAutherMobile();
        String orgFullName = organizationDO.getFullName();
        String orgCreditCode = organizationDO.getCreditCode();
        String orgAuthMobile = orgKtCustomerDO.getAutherMobile();



        ContractPushReqDTO.SignFileInfo applySignFileInfo = ContractPushReqDTO.buildSignFileInfo(applyFileId, applyFileName)
                .addSignInfo(bidderCreditCode,bidderName, "委托人："+bidderName,bidAuthMobile,"1");
        ContractPushReqDTO.SignFileInfo protocolSignFileInfo = ContractPushReqDTO.buildSignFileInfo(protocolFileId, protocolFileName)
                .addSignInfo(orgCreditCode, orgFullName, "乙方："+orgFullName,orgAuthMobile,"1")
                .addSignInfo(bidderCreditCode, bidderName, "甲方（签章）："+bidderName,bidAuthMobile,"1");
        List<ContractPushReqDTO.SignFileInfo> signFileInfoList = Lists.newArrayList(applySignFileInfo,protocolSignFileInfo);

        ContractPushReqDTO reqDTO = ContractPushReqDTO.buildReqDTO("申请书和协议书签署", signFileInfoList);
        //2.推送签署数据
        ContractPushRespDTO pushResp = contractPushService.doService(traceId, reqDTO);
        String sid = pushResp.getSid();

        //加签担保机构印章
        boolean ztPdfSignTF = pdfAutoStampService.pdfAutoStamp(acceptOrderNo, sid,"1", orgCreditCode, orgKtCustomerDO.getToken());
        if(!ztPdfSignTF){
            throw new RuntimeException("加盖机构印章失败");
        }

        //创建合同记录
        AcceptOrderContract acceptOrderContract = AcceptOrderContract.builder()
                .id(IdGenerate.getId()).acceptOrderNo(curDO.getAcceptOrderNo())
                .localContractId(applyFileId.concat(",").concat(protocolFileId))
                .contractType(ContractType.SQ.name()).contractStatus(ContractStatus.CREATED.name())
                .startDate(Date.from(Instant.now())).channelContractId(sid)
                .build();
        acceptOrderContractService.insert(acceptOrderContract);


        //3.获取签署url并更新合同记录
        ContractGetUrlRespDTO getUrlRespDTO = contractGetUrlService.getContractSignUrl(traceId, acceptOrderNo, bidderCreditCode, sid);
        String signUrl = getUrlRespDTO.getUrl();
        acceptOrderContract.setContractName(signUrl);
        acceptOrderContract.setContractStatus(ContractStatus.SIGNING.name());
        acceptOrderContract.setGmtModified(Date.from(Instant.now()));
        acceptOrderContractService.updateById(acceptOrderContract);

        return signUrl;


    }

}
